import { useRef, useState } from "react";
import { deepClone } from "../utils";
import useThrottleFn from "./useThrottleFn";

type Option = {
  ITEM_HEIGHT: number;
  dataSource: any[];
  onChange: (newList: any[]) => void;
};
const useDrag = (option: Option) => {
  const { ITEM_HEIGHT, dataSource, onChange } = option;

  const [draggingIndex, setDraggingIndex] = useState(null);
  const [dragKey, setDragKey] = useState("");
  const [startY, setStartY] = useState(0);
  const temp = useRef([]);

  const handleMoveStart = (e, index, key) => {
    setDraggingIndex(index);
    setDragKey(key);
    setStartY(e.touches[0].clientY);
    temp.current = deepClone(dataSource);
  };

  const handleMoveEnd = () => {
    setDraggingIndex(null);
    setDragKey("");
  };
  // 拖动时计算新位置
  const handleMove = useThrottleFn((e) => {
    if (draggingIndex === null) return;
    const diff = e.touches[0].clientY - startY;

    if (Math.abs(diff) < ITEM_HEIGHT / 2) return;

    let newIndex;
    if (diff > 0) {
      newIndex = Math.min(
        Math.max(0, draggingIndex + Math.round(diff / ITEM_HEIGHT)),
        dataSource.length - 1
      );
    } else {
      const offset = Math.round(diff / ITEM_HEIGHT);
      newIndex = Math.max(0, draggingIndex + offset);
    }

    // 交换数组元素并更新状态
    const newList = [...temp.current];
    newList.splice(draggingIndex, 1);
    newList.splice(newIndex, 0, temp.current[draggingIndex]);

    onChange?.(newList);
  }, 200);

  return {
    dragKey,
    draggingIndex,
    handleMoveStart,
    handleMoveEnd,
    handleMove,
  };
};

export default useDrag;
